package com.tinyideatech.admin.controller.mall;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tinyideatech.common.core.controller.BaseController;
import com.tinyideatech.common.core.entity.ApiResult;
import com.tinyideatech.common.core.entity.PageResult;
import com.tinyideatech.common.core.text.Convert;
import com.tinyideatech.common.utils.StringUtils;
import com.tinyideatech.system.entity.MallClassify;
import com.tinyideatech.system.entity.MallGoods;
import com.tinyideatech.system.service.IMallClassifyService;
import com.tinyideatech.system.service.IMallGoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @author zhangy-5
 * @date 2019-08-26
 */

@Controller
@RequestMapping("/mall/goods")
public class MallGoodsController extends BaseController {

    @Autowired
    private IMallGoodsService goodsService;
    @Autowired
    private IMallClassifyService classifyService;

    @GetMapping()
    public String list(ModelMap map) {
        map.addAttribute("classifyList", classifyService.selectList());
        return "mall/goods/list";
    }

    @GetMapping("/add")
    public String add(
            ModelMap map
    ) {
        map.addAttribute("classifyList", classifyService.selectList());
        return "mall/goods/add";
    }


    @GetMapping("/edit/{id}")
    public String mallGoodsEdit(
            @PathVariable("id") Long id,
            ModelMap map
    ) {
        MallGoods mallGoods = goodsService.getById(id);
        map.addAttribute("classifyList", classifyService.selectList());
        map.addAttribute("goods", mallGoods);
        return "mall/goods/edit";
    }

    @ResponseBody
    @PostMapping("/list")
    public PageResult list(MallGoods mallGoods) {
        QueryWrapper<MallGoods> qw = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(mallGoods.getGoodsName())) {
            qw.like("goods_name", mallGoods.getGoodsName());
        }
        if (StringUtils.isNotNull(mallGoods.getClassifyId())) {
            qw.like("classify_id", mallGoods.getClassifyId());
        }

        Map<Long, String> classifyMap = new HashMap<>();
        List<MallClassify> classifyList = classifyService.list(null);
        for (MallClassify classify : classifyList) {
            classifyMap.put(classify.getClassifyId(), classify.getClassifyName());
        }

        IPage<MallGoods> page = startPage();
        IPage<MallGoods> mallGoodsPage = goodsService.page(page, qw);
        for (MallGoods goods : mallGoodsPage.getRecords()) {
            if (classifyMap.containsKey(goods.getClassifyId())) {
                goods.setClassifyName(classifyMap.get(goods.getClassifyId()));
            }
        }
        return page(mallGoodsPage);
    }


    @ResponseBody
    @PostMapping("/save")
    public ApiResult save(
            MallGoods goods
    ) {
        // 11-1 ---------------------------------------
        MallClassify mallClassify = classifyService.getOne(new QueryWrapper<MallClassify>().eq("classify_id", goods.getClassifyId()));
        int count = mallClassify.getModelCount();
        count++;
        mallClassify.setModelCount(count);
        classifyService.saveOrUpdate(mallClassify);
        goods.setClassifyName(mallClassify.getClassifyName());
        goodsService.saveOrUpdate(goods);
        // -----------------------------------------------
        return success();
    }

    @ResponseBody
    @PostMapping("/remove")
    public ApiResult remove(
            String ids
    ) {
        Long[] mallGoodsIds = Convert.toLongArray(ids);
        // 11-1 增加删除逻辑
        Collection<MallGoods> queryGoods = goodsService.listByIds(Arrays.asList(mallGoodsIds));
        List<Long> classifyIds = new ArrayList<>();
        for (MallGoods mallGoods : queryGoods) {
            classifyIds.add(mallGoods.getClassifyId());
        }
        goodsService.removeByIds(Arrays.asList(mallGoodsIds));
        Collection<MallClassify> result = classifyService.listByIds(classifyIds);
        int count;
        for (MallClassify mallClassify : result) {
            count = mallClassify.getModelCount();
            count--;
            if (count < 0) {
                count = 0;
            }
            System.out.println("rm count: " + count);
            mallClassify.setModelCount(count);
            classifyService.saveOrUpdate(mallClassify);
            System.out.println("rm mallClassify: " + mallClassify);
        }
        // -----------------------------------------------
        return success();
    }

    @PostMapping("/changeStatus")
    @ResponseBody
    public ApiResult changeStatus(MallGoods mallGoods) {
        goodsService.changeStatus(mallGoods);
        return success();
    }

    @GetMapping("/getName")
    @ResponseBody
    public ApiResult getId(@RequestParam long id) {
        String name = classifyService.getOne(new QueryWrapper<MallClassify>().eq("classify_id", id)).getClassifyName();
        return success(name);
    }


    @GetMapping("/search")
    @ResponseBody
    public ApiResult search(@RequestParam(defaultValue = "") String keywords,
                            @RequestParam(defaultValue = "") String recommend,
                            @RequestParam(defaultValue = "") String category) {
        List<MallGoods> result = goodsService.searchList(keywords, recommend, category);
        return ApiResult.success(result);
    }


    @GetMapping("/selectJpgUrl")
    @ResponseBody
    public ApiResult selectJpgUrl(@RequestParam(value = "myFileName") MultipartFile mf,
                                  HttpServletRequest request) {
        String realPath = request.getSession().getServletContext().getRealPath("myFileName");
        String filename = mf.getOriginalFilename();
        String[] names = filename.split("\\.");//
        String tempNum = (int) (Math.random() * 100000) + "";
        String uploadFileName = tempNum + System.currentTimeMillis() + "." + names[names.length - 1];
        File targetFile = new File(realPath, uploadFileName);// 目标文件
        try {
            mf.transferTo(targetFile);
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Map<String, String> map = new HashMap<String, String>();
        map.put("errno", "0");
        System.out.println(uploadFileName);
        map.put("data", "http://localhost:8080/static/myFileName/" + uploadFileName);
        map.put("url", "http://localhost:8080/static/myFileName/" + uploadFileName);
        return ApiResult.success(map);

    }
}
